﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using University.Workshop.Business;
using University.Workshop.Model;
using University.Workshop.DataAccess;
using System.Collections.Generic;
using System.Collections.ObjectModel;

namespace University.Workshop.WebApp
{
    public partial class RegisterProduct : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!User.Identity.IsAuthenticated)
                FormsAuthentication.RedirectToLoginPage();
            errorMsg.Visible = false;

        }

        protected void submit_Click(object sender, EventArgs e)
        {
            try
            {
                string currency;
                if(rBolivianos.Checked)
                    currency="Bolivianos";
                else
                    currency="Dollars";
                Collection<HttpPostedFile> images = new Collection<HttpPostedFile>();
                HttpFileCollection uploadFilCol = Request.Files;
                for(int i = 0; i < uploadFilCol.Count; i++)
                {
                    HttpPostedFile file = uploadFilCol[i];
                    images.Add(file);
                }
                images = ProductRegistrationManager.GetUploadedFiles(images);
                bool hasImages = images.Count != 0;
                Product p = ProductRegistrationManager.RegisterNewProduct(xName.Text, xPrice.Text, description.Text, category.SelectedValue, hasImages, currency, UserDataAccess.GetUserByEmail(User.Identity.Name).Id, xQuantity.Text);
                ImageUploadHandler.UploadImages(images, Server, p.ProductId);
                Response.Redirect("ProductRegistrationSuccess.aspx");
            }
            catch (Exception ex)
            {
                errorMsg.Text = ex.Message;
                errorMsg.Visible = true;
            }
        }

        protected void cancel_Click(object sender, EventArgs e)
        {
            Response.Redirect("UserCP.aspx");
        }
    }
}